package com.lance.answer.question_valid;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.lance.answer.dto.Section;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpClientUtil;
import com.lance.answer.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class QuestionValidFetch {

    /**
     * 校验课程刷题情况
     *
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //学科中文名
        String subjectName = "毛泽东思想和中国特色社会主义理论体系概论";
        //专业中文名
        String majorName = "retry";
        //并发开启的浏览器数量
        int sync = 8;

        //是否提交答案
        boolean commit = false;
        //是否推送微信消息
        boolean push = false;
        //驱动路径
        String driverPath = null;

        //初始化日志配置
        Constant.initLog();

        StringBuilder sb = new StringBuilder();
        sb
                .append("校验课程")
                .append(" : ")
                .append(subjectName)
                .append("\n")

                .append("校验专业")
                .append(" : ")
                .append(majorName)
                .append("\n")

                .append("并发开启浏览器")
                .append(" : ")
                .append(sync)
                .append("\n");

        String message = sb.toString();
        System.out.println(message);
        if (push) {
            HttpClientUtil.send(message);
        }
        start(subjectName, majorName, sync, driverPath, commit, push);
    }

    public static void start(String subjectName, String majorName, int sync, String driverPath, boolean commit, boolean push) throws Exception {


        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + "users/" + majorName + ".user");
        List<String> users = IOUtils.readLines(inputStream2, "utf-8");

        File file = new File("src/main/resources/" + subjectName + "/valid_sections/");
        Collection<File> files = FileUtils.listFiles(file, null, false);
        Set<String> set = new HashSet<>();
        if (!CollectionUtils.isEmpty(files)) {
            for (File file1 : files) {
                String fileName = file1.getName();
                String userName = fileName.replace(".json", "");
                set.add(userName.trim());
            }
        }

        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }

        log.info("本次加载用户：{} 人", users.size());
        log.info("本次程序将加载 {} 个线程同时运行", group.size());


        StringBuilder sb2 = new StringBuilder();
        sb2.append("本次加载用户： " + users.size() + "人")
                .append("\n");

        String message2 = sb2.toString();
        System.out.println(message2);
        if (push) {
            HttpClientUtil.send(message2);
        }

        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                try {
                    for (String user : batchUser) {
                        String[] strs = user.split(",");
                        String userCode = strs[0];
                        String pwd = strs[1];
                        if (pwd.length() > 8) {
                            pwd = strs[1].substring(6, 14);
                        }
                        if (set.contains(userCode.trim())) {
                            log.info("用户：{} 已经处理过,跳过");
                            continue;
                        }
                        //ChromeDriver driver = Util.getDriver(driverPath);
                        run(subjectName, driverPath, userCode, pwd, commit, push);
                        log.info("用户：{} 分析完毕，当前进度：{} / {}", userCode, users.size());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

//        int i = 0;
//        for (String user : users) {
//            i++;
//            String[] strs = user.split(",");
//            String userCode = strs[0];
//            String pwd = strs[1];
//            if (pwd.length() > 8) {
//                pwd = strs[1].substring(6, 14);
//            }
//            if (set.contains(userCode.trim())) {
//                log.info("用户：{} 已经处理过,跳过",userCode);
//                continue;
//            }
//            run(subjectName, driverPath, userCode, pwd, commit, push);
//            log.info("用户：{} 分析完毕，当前进度：{} / {}",userCode,i,users.size());
//        }

    }

    public static void run(String subjectName, String driverPath, String userName, String password, boolean commit, boolean push) throws Exception {
        while (LocalDateTime.now().getHour() >= 3 && LocalDateTime.now().getHour() < 5) {
            log.info("当前时间：{} 国开网维护中 程序暂时休眠20min。。。", LocalDateTime.now().toString());
            TimeUnit.MINUTES.sleep(20);
        }
        //ChromeDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        ChromeDriver driver = Util.getDriver(driverPath);
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);

        //chromeDriver.navigate().refresh();
        boolean click = false;
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            String mediaTitle = we.findElement(By.className("media-title")).getText();
            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            try {
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                click = true;
                Util.switchToLast(driver);
                break;

            } catch (Exception e) {
                System.out.println("抛异常了");
                e.printStackTrace();
                File file = new File("d:\\user.txt");
                FileOutputStream outputStream = new FileOutputStream(file, true);
                //  String s= "用户："+userName+"毛概视频未刷\r\n";
                String s = userName + "," + password + "\r\n";
                outputStream.write(s.getBytes());
                driver.close();
                driver.quit();
            }
        }

        if (!click) {
            driver.close();
            driver.quit();
            return;
        }
        Thread.sleep(10000);
        //拉取URL

        List<WebElement> lis = driver.findElements(By.tagName("li"));
        if (CollectionUtils.isEmpty(lis)) {
            driver.close();
            driver.quit();
            return;
        }
        List<Section> sections = Lists.newArrayList();
        for (WebElement element : lis) {
            String classValue = element.getAttribute("class");
            if (!StringUtils.isNotEmpty(classValue)) {
                continue;
            }
            if (classValue.startsWith("activity") && classValue.contains("modtype_")) {
                List<WebElement> divs = element.findElements(By.tagName("div"));
                if (CollectionUtils.isEmpty(divs)) {
                    continue;
                }
                Section section = new Section();
                section.setType(classValue.split(" ")[1].trim());
                for (WebElement div : divs) {
                    String classValue2 = div.getAttribute("class");
                    if (!StringUtils.isNotEmpty(classValue2)) {
                        continue;
                    }
                    WebElement a = null;
                    if ("activityinstance".equalsIgnoreCase(classValue2.trim())) {
                        //System.out.println(div.toString());
                        //System.out.println(div.getText());
                        List<WebElement> aList = div.findElements(By.tagName("a"));
                        //System.out.println(aList);
                        //*[@id="module-74097"]/div/div/div[2]/div[1]/a
                        //*[@id="module-74097"]/div/div/div[2]/div[1]
                        if (!CollectionUtils.isEmpty(aList)) {
                            a = aList.get(0);
                        } else {
                            log.error("找不到A标签：{}", classValue2);
                            String rootPath = "src/main/resources/" + subjectName + "/valid_sections_error2/";
                            FileUtils.write(new File(rootPath + userName + ".json"), userName + "," + password, "utf-8");
                            log.info("用户：{}  写入分析结果失败", userName);
                            driver.close();
                            driver.quit();
                            return;
                        }
                        section.setUrl(a.getAttribute("href"));
//                        WebElement instancename = a.findElement(By.className("instancename"));
//                        System.out.println(instancename.getText());
//                        section.setSectionName(instancename.toString());
                    }
                    if ("actions".equalsIgnoreCase(classValue2.trim())) {
                        WebElement img = div.findElement(By.tagName("img"));
                        section.setMessage(img.getAttribute("alt"));
                    }
                }
                if (!StringUtils.isNotEmpty(section.getMessage())) {
                    section.setFinished(false);
                } else if (section.getMessage().trim().startsWith("未完成")) {
                    section.setFinished(false);
                } else if (section.getMessage().trim().startsWith("已完成")) {
                    section.setFinished(true);
                }

                if (StringUtils.isNotEmpty(section.getMessage())) {
                    String name = section.getMessage().replace("未完成：", "");
                    name = name.replace("已完成：", "");
                    name = name.replace("未完成：", "");
                    name = name.replace("。选择以标记为完成。", "");
                    name = name.replace("。选择以标记为未完成。", "");
                    section.setSectionName(name);
                }
                sections.add(section);
            }

        }
        String rootPath = "src/main/resources/" + subjectName + "/valid_sections/";
        //System.out.println(JSONObject.toJSONString(sections, SerializerFeature.PrettyFormat));
        FileUtils.write(new File(rootPath + userName + ".json"), JSONObject.toJSONString(sections, SerializerFeature.PrettyFormat), "utf-8");
        log.info("用户：{}  写入分析结果成功", userName);
        Thread.sleep(3000);
        driver.close();
        driver.quit();
    }


}
